package com.future.mayi.jpush;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;

import com.future.baselib.utils.LogUtils;
import com.future.mayi.app.App;
import com.future.mayi.utils.SharedPreferencesUtils;

import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by Administrator on 2018/3/22.
 */

public class JPushManager {

    //jpush_notification_icon.png

    private static final String TAG = "JPushManager";

    /**
     * 收到通知:应用打开的情况下，更新显示的新消息数量。
     */
    public void notificationReceived(Context context, String extraMsg) {

    }

    public static final String EXTRA_EXTRA = "extra_extra";

    /**
     * 打开通知，应用未启动，先启动MainActivity,在MainActivity中做处理
     * 已经启动的，将MainActivity移到栈顶，并打开通知详情页面
     *
     * @param context
     * @param extraMsg
     */
    public void notificationOpened(Context context, String extraMsg) {
        if (isAppAlive(context, context.getPackageName())) {
            LogUtils.d(TAG, "appAlive");

//            Intent mainIntent = new Intent(context, MainActivity.class);
//            mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            Intent detailIntent = Navigator.getNotificationListIntent(context, extraMsg);
            LogUtils.d(TAG, "detailIntent:" + detailIntent);
//            Intent[] intents = {mainIntent, detailIntent};
//            context.startActivities(intents);
            context.startActivity(detailIntent);
        } else {
            LogUtils.d(TAG, "appNotAlive");
            //如果app进程已经被杀死，先重新启动app，将DetailActivity的启动参数传入Intent中，参数经过
            //SplashActivity传入MainActivity，此时app的初始化已经完成，在MainActivity中就可以根据传入
            // 参数跳转到DetailActivity中去了
            Intent launchIntent = context.getPackageManager().
                    getLaunchIntentForPackage(context.getPackageName());
            launchIntent.setFlags(
                    Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            launchIntent.putExtra(EXTRA_EXTRA, extraMsg);
            context.startActivity(launchIntent);
        }

    }


    /**
     * 设置别名
     *
     * @param alias
     */
    public void setAlias(String alias) {
        LogUtils.d(TAG, "alias:" + alias);
        //已经设置过，不用再设置

        if (TextUtils.isEmpty(alias)) {
            JPushInterface.setAliasAndTags(App.getmContext(),
                    alias,
                    null,
                    new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set<String> set) {

                        }
                    });
            return;
        }
        if ((boolean) SharedPreferencesUtils.get(App.getmContext(), SharedPreferencesUtils.SpEnum.hasSetAlias, false)) {
            return;
        }
        LogUtils.d(TAG, "mHandler:" + alias);
        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    LogUtils.d(TAG, "setAliasSucceed");
                    SharedPreferencesUtils.set(App.getmContext(), SharedPreferencesUtils.SpEnum.hasSetAlias, true);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    break;
            }
        }
    };

    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(App.getmContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    break;
            }
        }
    };

    public boolean isAppAlive(Context context, String str) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        //String MY_PKG_NAME = "你的包名";
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(str)//如果想要手动输入的话可以str换成<span style="font-family: Arial, Helvetica, sans-serif;">MY_PKG_NAME，下面相同</span>
                    || info.baseActivity.getPackageName().equals(str)) {
                isAppRunning = true;
                break;
            }
        }
        return isAppRunning;
    }

}
